import cookie from '../lib/cookie';
import CONSTANT from '../constant/common';
// import { realpathSync } from 'fs';

let Token = '';

const clearUserInfo = () => {
  cookie(CONSTANT.COOKIE_USER_NICKNAME, null);
  cookie(CONSTANT.COOKIE_USER_NAME, null);
  cookie(CONSTANT.COOKIE_USER_ID, null);
  cookie(CONSTANT.COOKIE_USER_PHOTOURL, null);
  cookie(CONSTANT.COOKIE_USER_ROLE, null);
  cookie(CONSTANT.COOKIE_TOKEN, null);
  cookie(CONSTANT.COOKIE_USER_WOA_LIST, null);
};

const saveUserInfo = (info, isSeven) => {
  const conf = isSeven ? {
    maxage: 7 * 24 * 60 * 60 * 1000,
  } : {};
  cookie(CONSTANT.COOKIE_USER_NICKNAME, info[CONSTANT.COOKIE_USER_NICKNAME], conf);
  cookie(CONSTANT.COOKIE_USER_NAME, encodeURIComponent(info[CONSTANT.COOKIE_USER_NAME]), conf);
  cookie(CONSTANT.COOKIE_USER_ID, info[CONSTANT.COOKIE_USER_ID], conf);
  cookie(CONSTANT.COOKIE_USER_PHOTOURL, info[CONSTANT.COOKIE_USER_PHOTOURL], conf);
  cookie(CONSTANT.COOKIE_USER_ROLE, info[CONSTANT.COOKIE_USER_ROLE], conf);
  cookie(CONSTANT.COOKIE_USER_WOA_LIST, JSON.stringify(info[CONSTANT.COOKIE_USER_WOA_LIST]), conf);
  cookie(CONSTANT.COOKIE_TOKEN, Token, conf);
  cookie(CONSTANT.COOKIE_IS_FIRST_LOGIN, info.isFirstLogin);
};

const setToken = (token) => {
  Token = token;
  cookie(CONSTANT.COOKIE_TOKEN, token, { maxage: 7 * 24 * 60 * 60 * 1000 });
};

const getToken = () => {
  const ret = cookie(CONSTANT.COOKIE_TOKEN) || '';
  return ret;
};

const getIsFirstLogin = () => {
  const ret = cookie(CONSTANT.COOKIE_IS_FIRST_LOGIN) || false;
  return ret;
};

const isLogged = () => !!(cookie(CONSTANT.COOKIE_TOKEN) && cookie(CONSTANT.COOKIE_USER_ID));

export default {
  clearUserInfo,
  saveUserInfo,
  setToken,
  getToken,
  getIsFirstLogin,
  isLogged,
};
